package com.sky.service.impl;

import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 新增地址
     *
     * @param addressBook
     * @return
     */
    public void save(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.insert(addressBook);
    }

    /**
     * 查询当前登录用户的所有地址信息
     *
     * @return
     */
    public List<AddressBook> getUserAddress() {
        AddressBook addressBook = AddressBook.builder()
                .userId(BaseContext.getCurrentId())
                .build();

        return addressBookMapper.getUserAddress(addressBook);
    }


    /**
     * 根据id查询地址
     *
     * @param id
     */
    public AddressBook getById(Long id) {
        return addressBookMapper.getById(id);
    }


    /**
     * 根据id修改地址
     *
     * @param addressBook
     */
    public void updateById(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }


    /**
     * 查询默认地址
     *
     * @return
     */
    public AddressBook getDefaultAddress() {
        return addressBookMapper.getDefaultAddress();
    }

    /**
     * 设置默认地址
     *
     * @param addressBook
     */
    public void setDefaultAddress(AddressBook addressBook) {
        //先把当前默认地址的状态设置为0
        AddressBook oldAddressBook = addressBookMapper.getDefaultAddress();
        //检测是否有默认地址
        if (oldAddressBook != null) {
            oldAddressBook.setIsDefault(StatusConstant.DISABLE);
            addressBookMapper.update(oldAddressBook);
        }

        //设置默认地址
        addressBook.setIsDefault(StatusConstant.ENABLE);
        addressBookMapper.update(addressBook);
    }

    /**
     * 根据id删除地址
     *
     * @param id
     */
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }
}
